package com.huarui.roleTemplate.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.log4j.Logger;
import org.ewaf.framework.model.ListModel;
import org.ewaf.framework.service.BaseService;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;

import com.huarui.permission.dao.PermissionDao;
import com.huarui.permission.dataobject.Permission;
import com.huarui.roleTemplate.dao.IRoleTemplateDao;
import com.huarui.roleTemplate.model.RoleTemplate;
import com.huarui.roleTemplatePermission.dao.IRoleTemplatePermissionDao;
import com.huarui.roleTemplateTarget.dao.IRoleTemplateTargetDao;
import com.huarui.saleInvoice.util.SaleInvoiceMessageEnum;

public class RoleTemplateService extends BaseService {
	private final static Logger logger = Logger.getLogger(RoleTemplateService.class);
	@SuppressWarnings("unused")
	private IRoleTemplateTargetDao iRoleTemplateTargetDao;
	private IRoleTemplatePermissionDao iRoleTemplatePermissionDao;
	private PermissionDao permissionDao;
	private IRoleTemplateDao getDao() {
		return (IRoleTemplateDao) this.dao;
	}

	@SuppressWarnings("unchecked")
	public List<Map> pagingByCondition(ListModel lm, Map map) {
		Integer total = getDao().getCountByConditions(map);
		lm.setTotal(total);
		map.put("listModel", lm);
		List result = this.getDao().getListByConditions(map);
		lm.setResult(result);
		return result;
	}
	@SuppressWarnings("unchecked")
	public List<Map> getRoleTemPermByCondition(Map<String,Object> map){
		List<Map> list=this.getDao().getRoleTemPermByCondition(map);		
		Map<Integer,Map> tempMap=new HashMap<Integer, Map>();
		List<Map> parentList=new ArrayList<Map>();
		for(Map obj:list){
			if(obj.containsKey("id")){
				Integer id=(Integer) obj.get("id");
				tempMap.put(id, obj);
				Integer parentId=(Integer) obj.get("parentId");
				if(parentId==0){
					parentList.add(obj);
				}
			}
		}
		List<Map> resultList=genJsonString(tempMap,parentList);
		return resultList;
	}
	@SuppressWarnings("unchecked")
	public List genJsonString(Map mapAll,List<Map> list){
			List<Map> genJsonStringList=new ArrayList<Map>();
			Map tempMap=null;
			for(Map map:list){
				Integer isGroup=(Integer) map.get("isGroup");
				Integer id=(Integer) map.get("id");
				if(id==173){
					System.out.println(173);
				}
				if(isGroup==1){
					tempMap=new HashMap();
					tempMap.put("id", id);
					tempMap.put("text", map.get("name"));
					tempMap.put("cls", "folder");
					List tempList=new ArrayList();
					for(Iterator it=mapAll.entrySet().iterator();it.hasNext();){
						Map.Entry e=(Entry) it.next();
						Map obj=(Map) e.getValue();
						Integer parentId=(Integer) obj.get("parentId");
						if(parentId.intValue()==id){
							tempList.add(obj);
						}
					}
					//if(tempList.size()>0){
						List fList=genJsonString(mapAll,tempList);
						tempMap.put("children", fList);
					//}
				}else if(isGroup==0){
					tempMap=new HashMap();
					tempMap.put("id", id);
					tempMap.put("text", map.get("name"));
					tempMap.put("leaf", true);
					Integer idExit=(Integer) map.get("idExit");
					if(idExit!=null){
						tempMap.put("checked", true);
					}else{
						tempMap.put("checked", false);
					}
					mapAll.remove(map);
				}
				genJsonStringList.add(tempMap);
			}
		return genJsonStringList;
	}
	public Map<String,Object> save(final RoleTemplate roleTemplate,final List<Integer> checkedPreList,final List<Integer> unCheckedPreList){
		final Map<String,Object> resultMap=new HashMap<String, Object>();
		// 修改数据
		try {
			transactionTemplate.execute(new TransactionCallback() {
				@SuppressWarnings("unchecked")
				@Override
				public Object doInTransaction(TransactionStatus status){
					if(roleTemplate.getId()!=null){
						getDao().update(roleTemplate);
					}else {
						getDao().create(roleTemplate);
					}
					Map<String,Object> map=new HashMap<String, Object>();
					for(Integer permissionId:checkedPreList){
						map.put("roleTemplateId", roleTemplate.getId());
						map.put("permissionId", permissionId);
						if(iRoleTemplatePermissionDao.getById(map)==null){
							iRoleTemplatePermissionDao.createByMap(map);
						}
					}
					for(Integer permissionId:unCheckedPreList){
						map.put("roleTemplateId", roleTemplate.getId());
						map.put("permissionId", permissionId);
						iRoleTemplatePermissionDao.deleteByCondition(map);
					}
					
					return null;
				}
			});
		} catch (Exception e) {
			logger.error("保存权限模板出错",e);
			resultMap.put(SaleInvoiceMessageEnum.SUCCESS.getMsg(), SaleInvoiceMessageEnum.ERROR_MSG_DATABASE.getMsg());
			return resultMap;
		}
		resultMapInfo(resultMap);
		return resultMap;
	}
	public List<Map> getNoCheckPermissionList(){
		List<Permission> list=permissionDao.getAllPermissions();
		Map<Integer,Object> tempMap=new HashMap<Integer, Object>();
		List<Object> parentList=new ArrayList<Object>();
		for(Permission obj:list){
				tempMap.put(obj.getId(), obj);
				Integer parentId=obj.getParentId();
				if(parentId==0){
					parentList.add(obj);
				}
			
		}
		List<Map> resultList=genPremissionJsonString(tempMap,parentList);
		return resultList;
	}
	@SuppressWarnings("unchecked")
	public List genPremissionJsonString(Map mapAll,List<Object> list){
			List<Map> genJsonStringList=new ArrayList<Map>();
			Map tempMap=null;
			for(Object p:list){
				Permission permission=(Permission) p;
				Integer isGroup=permission.getIsGroup();
				Integer id=permission.getId();
				if(isGroup==1){
					tempMap=new HashMap();
					tempMap.put("id", id);
					tempMap.put("text", permission.getName());
					tempMap.put("sequence", permission.getSequence());
					tempMap.put("permission", permission);
					//tempMap.put("cls", "folder");
					List tempList=new ArrayList();
					for(Iterator it=mapAll.entrySet().iterator();it.hasNext();){
						Map.Entry e=(Entry) it.next();
						Permission obj=(Permission) e.getValue();
						Integer parentId=(Integer) obj.getParentId();
						if(parentId.intValue()==id.intValue()){
							tempList.add(obj);
						}
					}
					//if(tempList.size()>0){
						List fList=genPremissionJsonString(mapAll,tempList);
						tempMap.put("children", fList);
					//}
				}else if(isGroup==0){
					tempMap=new HashMap();
					tempMap.put("id", id);
					tempMap.put("text", permission.getName());
					tempMap.put("permission", permission);
					tempMap.put("sequence", permission.getSequence());
					tempMap.put("leaf", true);
					mapAll.remove(p);
				}
				genJsonStringList.add(tempMap);
			}
		return genJsonStringList;
	}
	public Map<String,Object> getRoleTemplateById(final Integer id){
		final Map<String,Object> resultMap=new HashMap<String, Object>();
		// 修改数据
		try {
			transactionTemplate.execute(new TransactionCallback() {
				@SuppressWarnings("unchecked")
				@Override
				public Object doInTransaction(TransactionStatus status){
					Map map=new HashMap();
					map.put("id", id);
					RoleTemplate roleTemplate=(RoleTemplate) getDao().getById(map);
					resultMap.put("data", roleTemplate);
					return null;
				}
			});
		} catch (Exception e) {
			logger.error("保存权限模板出错",e);
			resultMap.put(SaleInvoiceMessageEnum.SUCCESS.getMsg(), SaleInvoiceMessageEnum.ERROR_MSG_DATABASE.getMsg());
			return resultMap;
		}
		resultMapInfo(resultMap);
		return resultMap;
	}
	private void resultMapInfo(Map<String,Object> resultMap){
		if(!resultMap.containsKey(SaleInvoiceMessageEnum.SUCCESS.getMsg())){
			resultMap.put(SaleInvoiceMessageEnum.SUCCESS.getMsg(),SaleInvoiceMessageEnum.RESULT_TYPE_SUCCESS.getMsg());
		}
	}
	public void setiRoleTemplateTargetDao(
			IRoleTemplateTargetDao iRoleTemplateTargetDao) {
		this.iRoleTemplateTargetDao = iRoleTemplateTargetDao;
	}

	public void setiRoleTemplatePermissionDao(
			IRoleTemplatePermissionDao iRoleTemplatePermissionDao) {
		this.iRoleTemplatePermissionDao = iRoleTemplatePermissionDao;
	}

	public void setPermissionDao(PermissionDao permissionDao) {
		this.permissionDao = permissionDao;
	}
	
	
}